package JavaServlet.TimeServlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/studentSearch")
public class StudentSearch extends HttpServlet{
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String searchName = req.getParameter("searchName");
		
		ArrayList<Student>list = new ArrayList<Student>();
		ResultSet resultSet = null;
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "select id, name,age,gender from student where name like ?";
			statement = connection.prepareStatement(sql);
			statement.setString(1, "%"+searchName+"%");
			System.out.println(statement);
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				String gender = resultSet.getString("gender");
				int banjiId = resultSet.getInt("banjiId");
				Student student = new Student(id, name, age, gender,banjiId);
				list.add(student);
			}
			for (Student student : list) {
				System.out.println(student);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(connection, statement, resultSet);
		}
		
		// 放到一块内存区域里面
		req.setAttribute("list", list);
		// 请求转发到student_list.jsp页面进行展示
		req.getRequestDispatcher("/student_list.jsp").forward(req, resp);
	}
}
